//
//  MyDateView.m
//

#import "MyDateView.h"
#import "MyDateAdapter.h"
#import "MyDateHeader.h"

//静态变量
static NSSet<NSString *> *kHolidaySet = nil;

// 日期模型
@interface DayItem : NSObject
@property (nonatomic, strong) NSDate   *date;        // 当天 00:00:00
@property (nonatomic, copy  ) NSString *title;       // 几号
@property (nonatomic, copy  ) NSString *subTitle;    // 价格/文案
@property (nonatomic, assign) BOOL      isToday;     // 今天
@property (nonatomic, assign) BOOL      isEnabled;   // 是否可点
@property (nonatomic, assign) BOOL      isSelected;  // 是否选中
@end

@implementation DayItem
@end

// 月份模型
@interface SectionItem : NSObject
@property (nonatomic, strong) NSDate   *firstDay;    // 该月 1 号
@property (nonatomic, copy  ) NSString *sectionTitle;// 2025年09月
@property (nonatomic, strong) NSArray<DayItem *> *days; // 42 个格子（含前后空白）
@end

@implementation SectionItem
@end

static NSInteger kColumn = 7;
static NSInteger kMaxFutureMonth = 2; // 0-2，共 3 个月

@interface MyDateView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NSArray<SectionItem *> *sections;
@property (nonatomic, strong) NSCalendar *calendar;
@property (nonatomic, strong) NSDate *startDate;   // 已选开始
@property (nonatomic, strong) NSDate *endDate;     // 已选结束

@end

@implementation MyDateView
+ (instancetype)instanceView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"MyDateView" owner:nil options:nil] firstObject];
}
/**
 xib初始化当前控件
 */
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIView *v = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject];
        [self addSubview:v];
        v.frame = self.bounds;
        v.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    UICollectionViewFlowLayout *l = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat spacing = 0;//2.0;
    CGFloat inset   = 0;                   // 如果设了 sectionInset，这里要对应减去
    CGFloat availW  = self.collectionView.bounds.size.width - inset * 2 - spacing * (kColumn - 1);
    CGFloat itemW   = availW / kColumn;
    
    // 只有真正变化时才更新，避免重复计算
    if (!CGSizeEqualToSize(l.itemSize, CGSizeMake(itemW, itemW))) {
        l.itemSize = CGSizeMake(itemW, itemW);
        [self.collectionView.collectionViewLayout invalidateLayout];
    }
    
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    self.calendar = [NSCalendar currentCalendar];
    
    // 1. 读取假日表
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          NSString *path = [[NSBundle mainBundle] pathForResource:@"holidays" ofType:@"plist"];
          NSArray *arr = [NSArray arrayWithContentsOfFile:path];
          kHolidaySet = [NSSet setWithArray:arr];
      });
    
    
    [self initUI];
    [self buildData];
}

#pragma mark - 数据构造
- (void)buildData {
    NSMutableArray<SectionItem *> *tmp = [NSMutableArray array];
    
    NSDate *today = [self calendarStartOfDay:[NSDate date]];
    NSDate *firstDayThisMonth = [self firstDayOfMonth:today];
    
    for (NSInteger add = 0; add <= kMaxFutureMonth; add ++) {
        NSDate *firstDayOfMonth = [self.calendar dateByAddingUnit:NSCalendarUnitMonth value:add toDate:firstDayThisMonth options:0];
        NSDate *lastDay  = [self lastDayOfMonth:firstDayOfMonth];
        
        SectionItem *section = [SectionItem new];
        section.firstDay = firstDayOfMonth;
        section.sectionTitle = [self formatterYM:firstDayOfMonth];
        
        NSMutableArray<DayItem *> *dayArray = [NSMutableArray array];
        
        // 1. 周类型    周一、周二、周三、周四、周五、周六、周日
//        NSInteger weekday = [self.calendar component:NSCalendarUnitWeekday fromDate:firstDayOfMonth]; // 1=Sun
//        NSInteger emptyCount = (weekday - 1 + 6) % 7; // 周一为 0
//        for (NSInteger i = 0; i < emptyCount; i++) {
//            [dayArray addObject:[DayItem new]]; // 空模型
//        }
        // 1. 周类型  周日、周一、周二、周三、周四、周五、周六
        NSInteger weekday = [self.calendar component:NSCalendarUnitWeekday fromDate:firstDayOfMonth]; // 1=Sun
        NSInteger emptyCount = (weekday - 1); // 周日为 0
        for (NSInteger i = 0; i < emptyCount; i++) {
            [dayArray addObject:[DayItem new]]; // 空模型
        }
        
        // 2. 真正日期
        //NSOrderedAscending：早于今天， NSOrderedSame：今天；NSOrderedDescending：晚于今天
        NSDateComponents *comp = [NSDateComponents new];
        comp.day = 1;
        NSDate *day = firstDayOfMonth;
        while ([day compare:lastDay] != NSOrderedDescending) {
            DayItem *item = [DayItem new];
            item.date  = [self localStartOfDay:day];;
            item.title = [NSString stringWithFormat:@"%@",@([self.calendar component:NSCalendarUnitDay fromDate:day])];
            item.isToday = [self isToday:day];
            item.isEnabled = [day compare:today] != NSOrderedAscending; // 今天及以后
            item.subTitle = @"￥25起"; // 模拟价格
            [dayArray addObject:item];
            
            day = [self.calendar dateByAddingComponents:comp toDate:day options:0];
        }
        
        section.days = [dayArray copy];
        [tmp addObject:section];
    }
    self.sections = [tmp copy];
    
    [self.collectionView reloadData];
}


-(void)initUI
{
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat spacing = 0;//2;
//    CGFloat w = (self.collectionView.frame.size.width - spacing * (kColumn - 1)) / kColumn;
    CGFloat w = (self.collectionView.frame.size.width - spacing * (kColumn - 1)) / kColumn;
    layout.itemSize = CGSizeMake(w, w);
    layout.minimumInteritemSpacing = spacing;
    layout.minimumLineSpacing = spacing;
    layout.sectionInset = UIEdgeInsetsZero;
    
    //注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyDateAdapter" bundle:nil]
          forCellWithReuseIdentifier:@"cellID"];
    // 注册 header
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyDateHeader" bundle:nil]
          forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                 withReuseIdentifier:@"header"];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
}

#pragma mark - UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)cv {
    return self.sections.count;
}
- (NSInteger)collectionView:(UICollectionView *)cv numberOfItemsInSection:(NSInteger)section {
    return self.sections[section].days.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)ip
{
    MyDateAdapter *cell = [cv dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:ip];
    DayItem *item = self.sections[ip.section].days[ip.item];
    
    cell.labelTime.text      = item.title;
    cell.labelSubTitle.text  = item.subTitle;
    cell.userInteractionEnabled = item.isEnabled;
    cell.alpha               = item.isEnabled ? 1.0 : 0.4;
    
    // 0. 先清空背景，防止重用脏数据
    cell.backgroundColor = UIColor.clearColor;
    // 0.5 新增：周六/周日 → 红色
    BOOL isWeekend = ([self.calendar component:NSCalendarUnitWeekday fromDate:item.date] == 1 ||  // 周日
                      [self.calendar component:NSCalendarUnitWeekday fromDate:item.date] == 7);   // 周六
    
    if (item.date &&
        ((self.startDate && [item.date isEqualToDate:self.startDate]) ||
         (self.endDate   && [item.date isEqualToDate:self.endDate]))) {
        // 1. 头尾日期 → 蓝色底白字  选中状态处理
        cell.backgroundColor     = UIColor.systemBlueColor;
        cell.labelTime.textColor = UIColor.whiteColor;
        cell.labelSubTitle.textColor = UIColor.whiteColor;
    }
    // 2. 中间区间 → 浅蓝底黑字   区间状态处理
    else if (item.isSelected) {
        cell.backgroundColor = [UIColor colorWithRed:0.85 green:0.91 blue:1.0 alpha:1.0];
        cell.labelTime.textColor = UIColor.blackColor;
        cell.labelSubTitle.textColor = UIColor.blackColor;
    }
    // 3. 其余状态（今天/过期/普通）文字颜色保持你原来逻辑
    else if (item.isToday) {
        cell.labelTime.textColor = UIColor.systemBlueColor;
        cell.labelSubTitle.textColor = UIColor.systemBlueColor;
    }
    else if (!item.isEnabled) {
        // 3. 其余状态（今天/过期/普通）文字颜色保持你原来逻辑
        cell.labelTime.textColor = UIColor.lightGrayColor;
        cell.labelSubTitle.textColor = UIColor.lightGrayColor;
    }
    else  if (isWeekend) {
        // 3. 其余状态（今天/过期/普通）文字颜色保持你原来逻辑
        cell.labelTime.textColor = UIColor.systemRedColor;
        cell.labelSubTitle.textColor = UIColor.blackColor;
    }
    // 4新增：国家假日 → 红色
    else if ([kHolidaySet containsObject:[self yyyyMMddString:item.date]]) {
        cell.labelTime.textColor = UIColor.systemRedColor;
        cell.labelSubTitle.textColor = UIColor.blackColor;
    }
    else {
        // 默认状态
        cell.labelTime.textColor = UIColor.blackColor;
        cell.labelSubTitle.textColor = UIColor.blackColor;
    }
    
    return cell;
}

//header
- (UICollectionReusableView *)collectionView:(UICollectionView *)cv
           viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)ip {
    if (![kind isEqualToString:UICollectionElementKindSectionHeader]) return nil;
    MyDateHeader *h = [cv dequeueReusableSupplementaryViewOfKind:kind
                                             withReuseIdentifier:@"header"
                                                    forIndexPath:ip];
    h.labelDate.text = self.sections[ip.section].sectionTitle;
    return h;
}

- (CGSize)collectionView:(UICollectionView *)cv layout:(UICollectionViewLayout *)l referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(cv.frame.size.width, 44);
}

- (void)collectionView:(UICollectionView *)cv didSelectItemAtIndexPath:(NSIndexPath *)ip {
    DayItem *item = self.sections[ip.section].days[ip.item];
    if (!item.isEnabled || !item.date) return;
    
    // 第三次点击 → 清空
    if (self.startDate && self.endDate) {
        self.startDate = nil;
        self.endDate   = nil;
    } else if (!self.startDate) {
        self.startDate = [self localStartOfDay:item.date];//item.date;
    } else if (!self.endDate) {
        // 保证结束≥开始
        if ([item.date compare:self.startDate] == NSOrderedAscending) {
            self.endDate   = [self localStartOfDay:self.startDate];//self.startDate;
            self.startDate =[self localStartOfDay:item.date];// item.date;
        } else {
            self.endDate = [self localStartOfDay:item.date];//item.date;
        }
    }
    
    [self reloadDataToUpdateSelection];
    NSDateFormatter *f = [NSDateFormatter new];
    f.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    f.timeZone   = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; // 换成你的时区 不然在点击的日历由于区域问题，会少一天
//    NSLog(@"回调 start=%@", [f stringFromDate:self.startDate]);
//    NSLog(@"回调 end=%@", [f stringFromDate:self.endDate]);
    
    if (self.onRangeSelected) self.onRangeSelected([f stringFromDate:self.startDate],[f stringFromDate:self.endDate]);
    
}

#pragma mark - 工具
- (NSDate *)firstDayOfMonth:(NSDate *)date {
    NSDateComponents *comp = [self.calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:date];
    comp.day = 1;
    return [self.calendar dateFromComponents:comp];
}

- (NSDate *)lastDayOfMonth:(NSDate *)date {
    NSDateComponents *comp = [NSDateComponents new];
    comp.month = 1;
    comp.day   = -1;
    return [self.calendar dateByAddingComponents:comp toDate:[self firstDayOfMonth:date] options:0];
}

- (BOOL)isToday:(NSDate *)date {
    return [self.calendar isDateInToday:date];
}

- (NSString *)formatterYM:(NSDate *)date {
    static NSDateFormatter *f;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        f = [NSDateFormatter new];
        f.dateFormat = @"YYYY年MM月";
    });
    return [f stringFromDate:date];
}

//获取今天的天数  不包括时间
- (NSDate *)calendarStartOfDay:(NSDate *)date {
    return [self.calendar startOfDayForDate:date];
}


- (void)reloadDataToUpdateSelection {
    for (SectionItem *sec in self.sections) {
        for (DayItem *day in sec.days) {
            if (!day.date) continue;
            BOOL inRange = self.startDate && self.endDate &&
                          ([day.date compare:self.startDate] != NSOrderedAscending &&
                           [day.date compare:self.endDate]  != NSOrderedDescending);
            day.isSelected = inRange;
        }
    }
    [self.collectionView reloadData];
}

//一旦你的“本地时区”比 UTC 晚（东八区 +0800），00:00:00 UTC 在控制台里就会显示成 08:00:00 的同一天； 反之如果你处在 负时区（如 UTC-2），00:00:00 UTC 会被格式化成 前一天的 22:00，肉眼看上去就“差了一天”。
// 工具：本地零点
- (NSDate *)localStartOfDay:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comp = [cal components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                                   fromDate:date];
    return [cal dateFromComponents:comp];
}

- (NSString *)yyyyMMddString:(NSDate *)date {
    static NSDateFormatter *f;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        f = [NSDateFormatter new];
        f.dateFormat = @"yyyy-MM-dd";
        f.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    });
    return [f stringFromDate:date];
}

@end
